﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using WWB.SitePointPrivateMessages.Core.Infrastructure.Logging;
using WWB.SitePointPrivateMessages.Core.Model.Messages;
using WWB.SitePointPrivateMessages.Core.Service;

namespace WWB.SitePointPrivateMessages.Core.Model.DataImport
{
    [XmlRoot("privatemessages")]
    public class SitePointMessageExport
    {
        public SitePointMessageExport()
        {
            Folders = new ExportedFolder[0];
        }

        [XmlElement("folder")]
        public ExportedFolder[] Folders { get; set; }

        /// <summary>
        /// Imports messages from a SitePointMessageExport
        /// </summary>
        /// <param name="searcher">Message searcher</param>
        /// <param name="outputLog">Logging output vector</param>
        /// <returns>A message database matching the export</returns>
        /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="export"/> or <paramref name="outputLog"/> are null.</exception>
        public MessageDatabase ImportMessages(IMessageSearcher searcher, ILogger outputLog)
        {
            if (searcher == null) throw new ArgumentNullException("searcher");
            if (outputLog == null)
            {
                throw new ArgumentNullException("outputLog");
            }
            outputLog.LogMessage("Starting Message Import at {0}.", DateTime.Now);
            var folders = new List<Folder>(Folders.Count());
            var users = new List<ForumUser>();
            foreach (var f in Folders)
            {
                outputLog.LogMessage("Beginning to load folder '{0}'", f.Name);
                folders.Add(f.ConvertToFolder(users, outputLog));
                outputLog.LogMessage("Folder '{0}' added.", f.Name);
            }
            outputLog.LogMessage("Completed message import at {0}", DateTime.Now);
            return new MessageDatabase(searcher, folders, users);
        }
    }
}
